package com.baicai.baicaiknowledgeai.controller;

import com.aliyun.bailian20231229.models.ListIndexDocumentsResponse;
import com.aliyun.bailian20231229.models.ListIndicesResponse;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.baicai.baicaiknowledgeai.entity.User;
import com.baicai.baicaiknowledgeai.service.IKnowDiyManageService;
import com.baicai.baicaiknowledgeai.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/knowledge-manage")
public class KnowManageController {

    private static final Logger logger = LoggerFactory.getLogger(KnowManageController.class);

    private static final String UPLOAD_DIRECTORY;

    static {
        // 使用系统临时目录或指定绝对路径
        String tempDir = System.getProperty("java.io.tmpdir");
        UPLOAD_DIRECTORY = tempDir + File.separator + "uploads" + File.separator;

        try {
            Path uploadPath = Paths.get(UPLOAD_DIRECTORY);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 设置目录权限
            uploadPath.toFile().setWritable(true, false);
            uploadPath.toFile().setReadable(true, false);
            uploadPath.toFile().setExecutable(true, false);
        } catch (IOException exception) {
            throw new RuntimeException("无法创建上传目录: " + exception.getMessage(), exception);
        }
    }

    private final IKnowDiyManageService knowDiyManageService;
    private final IUserService userService;

    @Autowired
    public KnowManageController(IKnowDiyManageService knowDiyManageService, IUserService userService) {
        this.knowDiyManageService = knowDiyManageService;
        this.userService = userService;
    }


    @GetMapping("/documents")
    public ResponseEntity<Object> listDocuments(@RequestParam String username) {
        try {
            logger.info("开始获取用户 {} 的文档列表", username);

            User user = userService.findByUsername(username);
            if (user == null) {
                logger.error("用户 {} 不存在", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户不存在"));
            }

            if (user.getKnowledgeBaseId() == null) {
                logger.info("用户 {} 尚未创建知识库", username);
                return ResponseEntity.ok(createSuccessResponse("用户尚未创建知识库", null));
            }

            ListIndexDocumentsResponse response = knowDiyManageService.listKnowledgeBaseFiles(user);
            logger.info("成功获取用户 {} 的文档列表，共 {} 个文档",
                    username,
                    response.getBody().getData().getTotalCount());

            return ResponseEntity.ok(createSuccessResponse("获取文档列表成功", response.getBody().getData().getDocuments()));
        } catch (Exception exception) {
            logger.error("获取文档列表失败: {}", exception.getMessage(), exception);
            return ResponseEntity.internalServerError().body(
                    createErrorResponse("获取文档列表失败: " + exception.getMessage()));
        }
    }

    @PostMapping("/delete")
    public ResponseEntity<Object> deleteDocument(
            @RequestParam String username,
            @RequestParam String documentId) {
        try {
            logger.info("用户 {} 请求删除文档 {}", username, documentId);

            User user = userService.findByUsername(username);
            if (user == null) {
                logger.error("用户 {} 不存在", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户不存在"));
            }

            if (user.getKnowledgeBaseId() == null) {
                logger.error("用户 {} 尚未创建知识库", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户尚未创建知识库"));
            }

            boolean isSuccess = knowDiyManageService.deleteFileFromKnowledgeBase(user, documentId);
            if (isSuccess) {
                logger.info("文档 {} 删除成功", documentId);
                return ResponseEntity.ok(createSuccessResponse("文档删除成功", null));
            } else {
                logger.error("文档 {} 删除失败", documentId);
                return ResponseEntity.internalServerError().body(createErrorResponse("文档删除失败"));
            }
        } catch (Exception exception) {
            logger.error("删除文档失败: {}", exception.getMessage(), exception);
            return ResponseEntity.internalServerError().body(
                    createErrorResponse("删除文档失败: " + exception.getMessage()));
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<Object> uploadDocument(
            @RequestParam String username,
            @RequestParam("file") MultipartFile file) {

        // 1. 初始化响应和日志记录
        logger.info("用户 {} 开始上传文件: {}", username, file.getOriginalFilename());
        Path tempFile = null;

        try {
            // 2. 验证用户存在性
            User user = userService.findByUsername(username);
            if (user == null) {
                logger.error("用户 {} 不存在", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户不存在"));
            }

            // 3. 验证文件非空
            if (file.isEmpty()) {
                logger.error("上传文件为空");
                return ResponseEntity.badRequest().body(createErrorResponse("上传文件不能为空"));
            }

            // 4. 处理文件名（移除特殊字符）
            // 文件名处理（保留中文）
            String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            String sanitizedFilename = originalFilename
                    .replaceAll("[\\\\/:*?\"<>|]", "_")  // 关键修改处
                    .replaceAll("\\s+", "_");


            // 5. 创建临时文件（更安全的方式）
            tempFile = Files.createTempFile(Paths.get(UPLOAD_DIRECTORY),
                    "upload_" + System.currentTimeMillis() + "_",
                    "_" + sanitizedFilename);

            logger.debug("临时文件创建成功: {}", tempFile);

            // 6. 传输文件（使用Files.copy更可靠）
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
                logger.info("文件已保存到临时位置: {}", tempFile);
            }

            // 7. 上传到知识库
            String documentId = knowDiyManageService.uploadDocumentToKnowledgeBase(user, tempFile.toString());
            logger.info("文件成功上传到知识库，文档ID: {}", documentId);

            // 8. 构建响应
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("documentId", documentId);
            responseData.put("filename", originalFilename);
            responseData.put("size", file.getSize());
            responseData.put("contentType", file.getContentType());

            return ResponseEntity.ok(createSuccessResponse("文件上传成功", responseData));

        } catch (IOException e) {
            logger.error("文件操作失败: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("文件处理失败: " + e.getMessage()));
        } catch (Exception e) {
            logger.error("上传过程中出现意外错误: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("上传失败: " + e.getMessage()));
        } finally {
            // 9. 清理临时文件
            if (tempFile != null) {
                try {
                    Files.deleteIfExists(tempFile);
                    logger.debug("临时文件已删除: {}", tempFile);
                } catch (IOException e) {
                    logger.error("删除临时文件失败: {}", e.getMessage(), e);
                }
            }
        }
    }

    @GetMapping("/retrieve")
    public ResponseEntity<Object> retrieveContent(
            @RequestParam String username,
            @RequestParam String query) {
        try {
            logger.info("用户 {} 检索内容: {}", username, query);

            User user = userService.findByUsername(username);
            if (user == null) {
                logger.error("用户 {} 不存在", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户不存在"));
            }

            if (user.getKnowledgeBaseId() == null) {
                logger.error("用户 {} 尚未创建知识库", username);
                return ResponseEntity.badRequest().body(createErrorResponse("用户尚未创建知识库"));
            }

            RetrieveResponse response = knowDiyManageService.retrieveKnowledgeContent(user, query);
            logger.info("检索成功，找到 {} 条相关文档",
                    response.getBody().getData().getNodes().size());

            return ResponseEntity.ok(createSuccessResponse("检索成功", response.getBody()));
        } catch (Exception exception) {
            logger.error("检索失败: {}", exception.getMessage(), exception);
            return ResponseEntity.internalServerError().body(
                    createErrorResponse("检索失败: " + exception.getMessage()));
        }
    }

    private Map<String, Object> createSuccessResponse(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("data", data);
        return response;
    }

    private Map<String, Object> createErrorResponse(String error) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", error);
        return response;
    }
}